package com.easwift.qsp.das.szy;
import java.io.BufferedInputStream;

import com.easwift.qsp.enums.DeviceTypeEnum;
import com.easwift.qsp.enums.MonitorItemEnum;
import com.easwift.qsp.util.BitUtils;
import com.easwift.qsp.util.DataSourceUtils;
import com.easwift.qsp.util.LogUtils;

/**
 * 水准仪读数据线程
 * @author Administrator
 *
 */
public class SZYSocketReadThread extends Thread{

	private BufferedInputStream bis;

	public SZYSocketReadThread(BufferedInputStream bis) {
		super();
		this.bis = bis;
	}

	@Override
	public void run(){
		try{
			while(true){
				if(bis.available() != 0){
					byte[] bytes = new byte[bis.available()];
					bis.read(bytes,0,bis.available());
					System.out.println("读取到数据：");
					LogUtils.printFrame(bytes);
					//设备地址
					int address = Byte.toUnsignedInt(bytes[0]) + (Byte.toUnsignedInt(bytes[1]) << 8);
					//位移
					double d = 0;
					//温度
					double oc = 0;
					byte[] bbs = new byte[4];
					//从指定源数组赋值一个数组，复制从指定位置开始，到目标数组的指定位置结束
					System.arraycopy(bytes,14,bbs,0,4);
					bbs = BitUtils.reverseArray(bbs);
					d = BitUtils.byteArrayToFloat(bbs);
					System.arraycopy(bytes,18,bbs,0,4);
					bbs = BitUtils.reverseArray(bbs);
					oc = BitUtils.byteArrayToFloat(bbs);
					System.out.println(String.format("位移：%s",d));
					System.out.println(String.format("温度：%s",oc));
					String sql = String.format("insert into tb_device_data (address,value,device_type,monitor_item_id,create_time) values (%s,%s,%s,%s,%s)",String.valueOf(address),d,DeviceTypeEnum.WATER.getCode(),MonitorItemEnum.DISTANCE.getCode(),"now()");
					DataSourceUtils.getJdbcTemplate().execute(sql);
					sql = String.format("insert into tb_device_data (address,value,device_type,monitor_item_id,create_time) values (%s,%s,%s,%s,%s)",String.valueOf(address),oc,DeviceTypeEnum.WATER.getCode(),MonitorItemEnum.TEMPERATURE.getCode(),"now()");
					DataSourceUtils.getJdbcTemplate().execute(sql);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
